import time
import re
import requests
from requests import request
from datetime import datetime

def add_base_ip():
    new_ip_list = []
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'
    }
    i = 0
    while True:
        try:
            check_url = "https://httpbin.org/ip"
            respon_se = requests.get(url=check_url, headers=headers, verify=False, timeout=10)
            now_ip = respon_se.json()["origin"]
            new_ip_list.append(now_ip)
            break
        except KeyboardInterrupt:
            break
        except Exception as err:
            print(err)
            i += 1
            if i >= 10:
                break
            time.sleep(1)
    count = 0
    print('获取代理本机IP')
    while True:
        try:
            targetUrl = "http://myip.ipip.net"
            resp = requests.get(url=targetUrl, timeout=2, headers=headers)
            res = resp.content.decode("utf-8")
            now_ip2 = re.findall(" IP：(.*?)\s*?来自于", res)[0].strip()
            if now_ip2 not in new_ip_list:
                new_ip_list.append(now_ip2)
            break
        except Exception as err:
            count += 1
            if count > 10:
                break
            time.sleep(0.5)
    url = 'http://api.tianqiip.com/white/fetch?key=jisu9&brand=2&sign=06ea3d7100c49d8ff2bfd545bace6318'
    respon = requests.get(url=url, headers=headers)
    ip_res_list = respon.json()["data"]
    ip_num = len(ip_res_list)
    if ip_num > 8:
        for one_ip in new_ip_list:
            if one_ip not in "".join(ip_res_list):
                del_ip_list = ip_res_list[8:]
                del_url = "http://api.tianqiip.com/white/delete?key=jisu9&brand=2&sign=06ea3d7100c49d8ff2bfd545bace6318&ip=" + ','.join(del_ip_list)
                requests.get(url=del_url, headers=headers)
                print('删除白名单成功')
                break
    insert_url = "http://api.tianqiip.com/white/add?key=jisu9&brand=2&sign=06ea3d7100c49d8ff2bfd545bace6318&ip=" + ','.join(new_ip_list)
    requests.get(url=insert_url)

def get_proxy_ip(flag=None):
    try:
        add_base_ip()
        print('添加删除代理成功')
    except Exception as err:
        print('获取本机IP异常。。。。。%s' % err)
    proxie_url = "http://api.tianqiip.com/getip?secret=4b90285gtrtu238b&type=json&num=1&time=3&cs=1&ys=1&ts=1&port=2"
    num = 0
    while True:
        try:
            resu = requests.get(url=proxie_url)
            proxie_json = resu.json()
            if proxie_json["data"] != []:
                return proxie_json
        except KeyboardInterrupt:
            break
        except Exception as err:
            num += 1
            print('get proxy ip err num:::%s' % num)
        if flag:
            break

def judge_ip_time(ip_dict):
    # {'code': 1000, 'data': [{'ip': '106.226.238.50', 'port': 32886, 'prov': '江西', 'city': '景德镇', 'isp': '电信', 'expire': '2021-09-25 13:15:58'}]}
    expire = ip_dict['data'][0]['expire']
    expire_time = datetime.strptime(expire, '%Y-%m-%d %H:%M:%S')
    now_time = datetime.now()
    if expire_time > now_time:
        return False  # 没有过期
    else:
        return True  # IP过期了

if __name__ == '__main__':
    print(get_proxy_ip(flag=True))
